package toledo.post;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.gdata.data.acl.AclRole;
import com.google.gdata.data.acl.AclScope;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.util.ServiceException;

import toledo.rest.Course;
import toledo.util.DocumentList;
import toledo.util.DocumentListException;

public class AddCourseServlet extends HttpServlet
{
	private static final long serialVersionUID=1L;
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		String coursename = req.getParameter(Course.COURSENAME);
		String hashtag = req.getParameter(Course.HASHTAG).replace("#"," ").trim();
		
		DocumentListEntry folder = null;
		try
		{
			DocumentList dl = DocumentList.getService();
			folder = dl.createNew(coursename,"folder");
			dl.addAclRole(AclRole.READER,new AclScope(AclScope.Type.DEFAULT,null),folder.getResourceId());
			//String public_url = folder.getDocumentLink().getHref();
			//log.log(Level.INFO,public_url);
		}
		catch(DocumentListException e2)
		{
			e2.printStackTrace();
		}
		catch(ServiceException e)
		{
			e.printStackTrace();
		}
		
		
		Entity e = new Entity(Course.DATABASE);
		e.setProperty(Course.COURSENAME,coursename);
		e.setProperty(Course.HASHTAG,hashtag);
		e.setProperty(Course.DOCS_RES_ID,folder.getResourceId());
		//e.setProperty(Course.DOCS_PUBLIC_URL,folder.getDocumentLink().getHref());
		
		DatastoreServiceFactory.getDatastoreService().put(e);
		
		resp.sendRedirect("database.jsp");
	}
}
